'use strict';
const {
  Model
} = require('sequelize');
const bcrypt = require('bcryptjs');
const moment = require("moment")
moment.locale('zh-cn')

module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      models.User.hasMany(models.Post, {as: 'posts'})
      models.User.hasMany(models.Comment, {as: 'comments'})
    }
  }
  User.init({
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {msg: '用户名必须填写'},
        notEmpty: {msg: '用户名不能为空'},
        len: {args: [2, 45], msg: "用户名长度必须是2 ~ 45之间。"},
        async isUnique(value) {
          const user = await User.findOne({where: {name: value}})
          if(user) {
            throw new Error("用户名已经存在")
          }
        }
      }
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {msg: '邮箱必须填写'},
        notEmpty: {msg: '邮箱不能为空'},
        isEmail: {msg: '邮箱格式不正确'},
        async isUnique(value) {
          const user = await User.findOne({where: {email: value}})
          if(user) {
            throw new Error("邮箱已经存在，请直接登录")
          }
        }
      }
    },
    password: {
      type:  DataTypes.STRING,
      allowNull: false,
      set(value) {
        if(!value) {
          throw new Error("密码必须填写")
        }

        if(value.length < 6 || value.length > 18) {
          throw new Error("密码长度必须是6~18位之间")
        }

        this.setDataValue("password", bcrypt.hashSync(value, 10))
      }
    },
    role: {
      type: DataTypes.TINYINT,
      allowNull: false,
      validate: {
        notNull: {msg: '角色必须填写'},
        notEmpty: {msg: '角色不能为空'},
        isIn: {args: [[0, 100]], msg: "用户组的值必须是，普通用户：0 管理员：100。"}
      }
    },
    avatar: {
      type: DataTypes.STRING
    },
    createdAt: {
      type: DataTypes.DATE,
      get() {
        return moment(this.getDataValue('createdAt')).format("LL")
      }
    },
    updatedAt: {
      type: DataTypes.DATE,
      get() {
        return moment(this.getDataValue('updatedAt')).format("LL")
      }
    }
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};